package com.topsoft.email.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.lang3.StringEscapeUtils;

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper{

	public XssHttpServletRequestWrapper(HttpServletRequest request) {
		super(request);
	}
	  
    @Override  
    public String getHeader(String name) {  
        return StringEscapeUtils.escapeHtml4(super.getHeader(name));  
    }  
  
    @Override  
    public String getQueryString() {  
        return StringEscapeUtils.escapeHtml4(super.getQueryString());  
    }  
  
    @Override  
    public String getParameter(String name) {  
    	String value = super.getParameter(name);
    	value=StringEscapeUtils.escapeHtml4(super.getParameter(name));
    	value = value == null ? null : xssEncode(value);
        return value;
    }  
  
    @Override  
    public String[] getParameterValues(String name) {  
        String[] values = super.getParameterValues(name);  
        if(values != null) {  
            int length = values.length;  
            String[] escapseValues = new String[length];  
            for(int i = 0; i < length; i++){  
                escapseValues[i] = StringEscapeUtils.escapeHtml4(values[i]); 
              //xss漏洞拦截
                escapseValues[i] = escapseValues[i] == null ? null : xssEncode(escapseValues[i]);
            }  
            return escapseValues;  
        }  
        return super.getParameterValues(name);  
    }  
    
    
 
    
    
    /**
	    * 将容易引起xss漏洞的  半角字符  直接替换成  全角字符
	    *
	    * @param s
	    * @return
	    */
	    private static String xssEncode(String s) {
	        if (s == null || "".equals(s)) {
	            return s;
	        }
	        StringBuilder sb = new StringBuilder(s.length() + 16);
	        for (int i = 0; i < s.length(); i++) {
	            char c = s.charAt(i);
	            switch (c) {
	                case '>':
	                    sb.append('＞');//全角大于号
	                    break;
	                case '<':
	                    sb.append('＜');//全角小于号
	                    break;
	                case '\'':
	                    sb.append('‘');//全角单引号
	                    break;
	                case '\"':
	                    sb.append('“');//全角双引号
	                    break;
	                case '&':
	                    sb.append('＆');//全角
	                    break;
	                case '\\':
	                    sb.append('＼');//全角斜线
	                    break;
	                case '#':
	                    sb.append('＃');//全角井号
	                    break;
	                default:
	                    sb.append(c);
	                    break;
	            }
	        }
	        return sb.toString();
	    }

}
